package com.xiaojian.blog.service.impl;

import com.xiaojian.blog.dao.UserPOMapper;
import com.xiaojian.blog.exception.TipException;
import com.xiaojian.blog.model.UserPO;
import com.xiaojian.blog.model.UserPOExample;
import com.xiaojian.blog.service.UserService;
import com.xiaojian.blog.utils.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserPOMapper userPOMapper;

    @Override//保存用户数据
    @Transactional
    public Integer insertUser(UserPO userPO) {
        if (StringUtils.isNotBlank(userPO.getUsername()) &&
                StringUtils.isNotBlank(userPO.getEmail())) {
            //用户密码使用MD5加密
            String encodePwd = TaleUtils.MD5encode(userPO.getUsername() + userPO.getPassword());
            userPO.setPassword(encodePwd);
            userPOMapper.insertSelective(userPO);
        }
        return userPO.getUid();
    }

    @Override//通过主键查询用户
    public UserPO queryUserById(Integer uid) {
        UserPO userPO = null;
        if (null != uid) {
            userPO = userPOMapper.selectByPrimaryKey(uid);
        }
        return userPO;
    }

    @Override//用户登录
    public UserPO login(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new TipException("同户名和密码不能为空");
        }
        UserPOExample userPOExample = new UserPOExample();
        UserPOExample.Criteria criteria = userPOExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        long count = userPOMapper.countByExample(userPOExample);
        if (count < 1) {
            throw new TipException("不存在该用户");
        }
        String pwd = TaleUtils.MD5encode(username + password);
        criteria.andPasswordEqualTo(pwd);
        List<UserPO> users = userPOMapper.selectByExample(userPOExample);
        if (users.size() != 1) {
            throw new TipException("用户名或密码错误");
        }
        return users.get(0);
    }

    @Override//通过主键更新用户数据
    @Transactional
    public void updateByUid(UserPO userPO) {
        if (null == userPO || null == userPO.getUid()) {
            throw new TipException("userPO is null");
        }
        int i = userPOMapper.updateByPrimaryKeySelective(userPO);
        if (i != 1) {
            throw new TipException("update user by uid and return is not one");
        }
    }
}
